package com.shengwei.truck.driver.view.ui.task;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonTaskListData;
import com.shengwei.truck.driver.bean.task.TaskItem;
import com.shengwei.truck.driver.databinding.ExceptionTaskListBinding;
import com.shengwei.truck.driver.view.adapter.task.TaskListAdapter;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.vm.TaskViewModel;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 异常任务列表：审核未通过的任务列表
 */
public class ExcepTaskListActivity extends BaseActivity<TaskViewModel, ExceptionTaskListBinding> {
    int currentOperate = PULL_REFRESH; //0表示下拉刷新,1表示加载更多
    private static final int PULL_REFRESH = 0; //下拉刷新
    private static final int LOAD_MORE = 1;  //加载更多
    private TaskListAdapter mTaskAdapter;
    private List<TaskItem> mTaskList = new ArrayList<>();
    int mTaskState = 4; //代表榜单审核未通过
    int mPageNum = 0; //索引从0开始表示第一页
    int mPageSize = 20;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化控件
        initView();
        initLiveDataObersve();
    }

    @Override
    public int getContentViewId() {
        return R.layout.exception_task_list;
    }


    /**
     * 初始化控件
     */
    public void initView() {
        //配置下拉刷新控件的圆形转圈的颜色
        mDataBinding.refreshLayout.setOnRefreshListener(mRefreshListener);
        int colorCircle1 = this.getResources().getColor(R.color.colorPrimary);
        int colorCircle2 = this.getResources().getColor(R.color.colorPrimaryDark);
        int colorCircle3 = this.getResources().getColor(R.color.colorPrimary);
        mDataBinding.refreshLayout.setColorSchemeColors(colorCircle1,colorCircle2,colorCircle3);

        //配置任务列表控件Recyclerview
        mDataBinding.taskRecyclerView.setLayoutManager(new LinearLayoutManager(this));
      //  mDataBinding.taskRecyclerView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(this, R.color.divider_color)));
        mDataBinding.taskRecyclerView.setSwipeItemClickListener(mItemClickListener); // RecyclerView Item点击监听。
        mDataBinding.taskRecyclerView.useDefaultLoadMore(); // 使用默认的加载更多的View。
        mDataBinding.taskRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听

        //新任务列表
        mTaskAdapter = new TaskListAdapter(this,mTaskState);
        mDataBinding.taskRecyclerView.setAdapter(mTaskAdapter);
        //请求服务器加载数据到任务列表。
        refreshLoadData();
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听任务列表接口返回的列表数据
        mViewModel.getTaskListLiveData().observe(this, new Observer<Result<JsonTaskListData>>() {
            @Override
            public void onChanged(Result<JsonTaskListData> jsonTaskListDataResult) {
                jsonTaskListDataResult.handler(new OnCallback<JsonTaskListData>() {
                    @Override
                    public void onSuccess(JsonTaskListData data) {
                        if(currentOperate == PULL_REFRESH) {
                            dealTaskListForRefresh(data);
                        }
                        else {  //上拉加载更多
                            dealTaskListForLoadMore(data);
                        }
                        mDataBinding.refreshLayout.setRefreshing(false);
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                });
            }
        });
    }

    /**
     * 处理  "下拉刷新" 时 从服务器获取到的 “任务列表”，显示到 UI列表上
     * @param taskListData： “任务列表”数据
     */
    public void dealTaskListForRefresh(JsonTaskListData taskListData) {
        //是否有下一页
        int totalpages = taskListData.getTotalPages();
        boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;

        List<TaskItem> taskItemList =  taskListData.getContent();
        boolean isCurEmptyData = true;
        mTaskList.clear();

        if(taskItemList != null && taskItemList.size() > 0) {
            mDataBinding.taskRecyclerView.setVisibility(View.VISIBLE);
            mDataBinding.noDataLayout.setVisibility(View.GONE);
            isCurEmptyData = false;
            mTaskList.addAll(taskItemList);
        }
        else{
            mDataBinding.taskRecyclerView.setVisibility(View.GONE);
            mDataBinding.noDataLayout.setVisibility(View.VISIBLE);
        }
        mTaskAdapter.notifyDataSetChanged(mTaskList);
        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            mPageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }
    /**
     * 处理  "上滑加载更多" 时 从服务器获取到的 “任务列表”，显示到 UI列表上
     * @param taskListData： “任务列表”数据
     */
    public void dealTaskListForLoadMore(JsonTaskListData taskListData) {
        //是否有下一页
        int totalpages = taskListData.getTotalPages();
        boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;
        boolean isCurEmptyData = true;
        List<TaskItem> taskItemList =  taskListData.getContent();

        if(taskItemList != null && taskItemList.size() > 0) {
            int existSize = mTaskList.size();  //已有的条目个数
            isCurEmptyData = false;
            mTaskList.addAll(taskItemList);
            mTaskAdapter.notifyItemRangeInserted(existSize - 1,taskItemList.size());
        }
        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            mPageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }

    /**
     * 下拉刷新数据
     */
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshLoadData();
        }
    };

    /**
     * 上拉时加载更多
     */
    private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            currentOperate = LOAD_MORE;
            mViewModel.getTaskList(String.valueOf(mTaskState), mPageNum, mPageSize,0);
        }
    };

    /**
     * 列表项点击进入“异常任务详情页”（榜单未审核通过）
     */
    private SwipeItemClickListener mItemClickListener = new SwipeItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            TaskItem taskItem =  mTaskList.get(position);
            String id = taskItem.getId();
            Intent i = new Intent(ExcepTaskListActivity.this, ExcepTaskDetailActivity.class);
            i.putExtra("id",id);
            startActivity(i);
        }
    };

    /**
     * 第一次加载数据或下拉刷新
     */
    private void refreshLoadData() {
        mPageNum = 0;
        currentOperate = PULL_REFRESH;
        mViewModel.getTaskList(String.valueOf(mTaskState), mPageNum, mPageSize,0);
    }
}
